package com.xuecheng.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.CompanyDateDto;
import com.xuecheng.commons.model.dto.CompanyDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.vo.CompanyVo;
import com.xuecheng.commons.model.vo.PageResponseResult;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.system.domain.Company;
import com.xuecheng.system.mappers.CompanyMapper;
import com.xuecheng.system.service.CompanyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 教育机构 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-16
 */
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements CompanyService {

    @Override
    public ResponseResult companyList(PageRequest pageRequest, CompanyDto dto) {
        String[] split = dto.getApprovalStatus().split(",");
        //构造分页对象
        Page<Company> page=new Page<>(pageRequest.getPageNo(),pageRequest.getPageSize());
        //设置查询条件
        LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(dto.getApprovalStatus())){
             queryWrapper.in(Company::getApprovalStatus,split);
        }
        if (!StringUtils.isEmpty(dto.getCompanyName())){
            queryWrapper.eq(Company::getName,dto.getCompanyName());
        }
        //分页查询
        Page<Company> companyPage = this.page(page, queryWrapper);
        // 构建返回值
        List<Company> companyList = companyPage.getRecords();
        ArrayList<CompanyVo> vos = new ArrayList<>();
        for (Company company : companyList) {
            CompanyVo companyVo = BeanHelper.copyProperties(company, CompanyVo.class);
            companyVo.setCompanyId(company.getId());
            vos.add(companyVo);
        }
        return PageResponseResult.okResult(companyPage.getTotal(),vos); // 总条数 数据列表
    }

    @Override
    public ResponseResult company(CompanyDateDto dto) {
        //判断参数是否为空
        if (dto==null){
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        //将接收参数转换为实体类
        Company company = BeanHelper.copyProperties(dto, Company.class);
        company.setApprovalStatus("202002");
        
        //将数据存入数据库
        this.save(company);
        return ResponseResult.okResult();
    }
}
